﻿using System;
using System.Collections.Generic;
using System.Text;
using Future.Channel;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace Future.Host
{
    public class WcfService : Future.Contract.IWcfService
    {
        #region IWcfService 成员

        public byte[] ExecCommandByte(Task task, ref bool result, ref string errMsg)
        {
            Exec(ref task, ref result, ref errMsg);
            return Common.ZipTools.CompressionObject<Task>(task);
        }

        public string ExecCommandString(Channel.Task task, ref bool result, ref string errMsg)
        {
            Exec(ref task, ref result, ref errMsg);
            return LitJson.JsonMapper.ToJson(task);
        }

        public int XPing(int n)
        {
            return n;
        }

        #endregion

        private void Exec(ref Task task, ref bool result, ref string errMsg)
        {
            if (task == null)
            {
                result = false;
                errMsg = "Task 不能为空";
                return;
            }
            Future.DataAccess.DalBase dal = Cache.CacheManager.shareCacher().getDAL(task.DALName);

            if (dal != null)
            {
                dal.Exec(ref task, ref result, ref errMsg);
            }
            else
            {
                result = false;
                errMsg = "DAL 实例化没有成功";
                return;
            }
        }

        private static string GetRemoteIP()
        {
            OperationContext context = OperationContext.Current;
            MessageProperties property = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty remote = property[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return remote.Address;
        }

        private static int GetRemotePort()
        {
            OperationContext context = OperationContext.Current;
            MessageProperties property = context.IncomingMessageProperties;
            RemoteEndpointMessageProperty remote = property[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
            return remote.Port;
        }
    }
}
